from typing import List


class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        rows = []
        row_words = []
        row_char_cnt = 0
        for word in words:
            if row_char_cnt + len(row_words) + len(word) <= maxWidth:
                row_words.append(word)
                row_char_cnt += len(word)
            else:
                rows.append(row_words)
                row_words = [word]
                row_char_cnt = len(word)
        else:
            if row_words:
                rows.append(row_words)

        def words_to_row (row_words):
            blank_cnt = maxWidth - sum(len(x) for x in row_words)
            if len(row_words) == 1:
                return row_words[0] + ' ' * blank_cnt
            blank_section_cnt = len(row_words) - 1
            blank_section_lengths = [blank_cnt // blank_section_cnt] * blank_section_cnt
            for i in range(blank_cnt % blank_section_cnt):
                blank_section_lengths[i] += 1
            row = row_words[0]
            for i in range(1, len(row_words)):
                row += ' ' * blank_section_lengths[i - 1]
                row += row_words[i]
            return row

        if not rows:
            return []

        result = []
        for row in rows[:-1]:
            result.append(words_to_row(row))
        last_row = ' '.join(rows[-1])
        pad_len = maxWidth - len(last_row)
        last_row = last_row + ' ' * pad_len
        result.append(last_row)
        return result

words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
print(Solution().fullJustify(words, maxWidth))


words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
print(Solution().fullJustify(words, maxWidth))


words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
print(Solution().fullJustify(words, maxWidth))